#!/usr/bin/python
#_*_coding:UTF-8_*_
#for test ctrlgray
import urllib2
from pyDes import *
import httplib 
import sys
import re
data1 ='''<?xml version="1.0"?>
<request>
  <cmd>config</cmd>
  <base>
    <caller>123213</caller>
    <osid>Android</osid>
    <imei>121212</imei>
    <ua>asasa</ua>
    <sid>a139379318f32122</sid>
    <ap>1223</ap>
    <aid>100IME</aid>
    <imsi>460030134024205</imsi>
    <userid>123</userid>
    <lg>zh</lg>'''
data2='''
  </base>
  <param>
    <downfrom>0101</downfrom>
    <pkgpath>path</pkgpath>
    <imestate>1</imestate>
  </param>
</request>'''
param=sys.argv[1:]
uid=1111111111111111
version='5.2.2501'
df=01010000
uidlist='uid.txt'
##打印粉色文字
def print_red (all):
	print  '\033[1;35;40m',all,'\033[0m'
#打印绿色文字
def print_green (all):
	print  '\033[1;32;40m',all,'\033[0m'
#灰度检查函数，参数有uid,版本，渠道号，调用本脚本的参数
def gray_check (uid,version,df,param):
    data=data1+'<uid>'+str(uid)+'</uid>'+'\n'+'<version>'+str(version)+'</version>'+'\n'+'<df>'+str(df)+'</df>'+'\n'+data2#初始化请求包xml
    k=des("x%73g123",ECB,"\0\0\0\0\0\0\0\0",pad=None,padmode=PAD_PKCS5)#使用pyDes加密方法，定义加密K
    data_req=k.encrypt(data)#加密数据
    header = {"Content-Type":"text/xml","Content-Length":"%d" % len(data_req),"x-up-calling-line-id":"13966729806"}#初始化http请求头
    conn = httplib.HTTPConnection("172.16.66.21:8083")#初始化http对象
    conn.request(method="POST",url="/do.aspx?t=123",body='',headers=header)#发送请求
    conn.send(data_req)#发送请求xml
    response = conn.getresponse()#获取返回包
    gray=k.decrypt(response.read())#解密数据
    if re.findall('versioncheck',gray):#查询返回包是否返回版本非法
	print_red('versioncheck error')
    else:
	result=re.findall('\d{6}:\d{1}',gray)#利用python re模块匹配灰度码
	result.sort()
	for i in result:#按照脚本参数显示出含有参数的灰度码
	    if param:
		for j in param:
      		    if j in i:
			print_red(i)
	    else:#如果没有参数，则打印全部的返回灰度值
		print i
def read_uid ():
	uid_rd=open('/root/uid/uid1.txt','r')
	uids=uid_rd.readlines()
	return uids
for i in param:
	if len(i)==18:
		uid=param.pop(param.index(i))#取参数的列表的uid并将uid从参数列表中删除
	elif len(i)==8 and re.match(r'\d\.\d\.\d{4}',i):
		version=param.pop(param.index(i))#取参数的版本version,并从列表中删除
	elif len(i)==8:
		df=param.pop(param.index(i))#取参数列表的渠道号，并从列表中删除
	else:
		pass
if uidlist in param:#判断是否使用uid.txt这个文件里面的uid
    param.remove(uidlist)
    uids=open('/root/uid/uid.txt','r').readlines()
    for uid in uids:
	print uid
	gray_check(uid,version,df,param)	
else:
    pass
    gray_check(uid,version,df,param)
